//
//  LockView.m
//  手指解锁
//
//  Created by Jorn.Wu on 15/6/29.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "LockView.h"

@interface LockView()

@property (nonatomic, strong) NSMutableArray *btns;//用于存储选中的按钮
@property (nonatomic, assign) CGPoint moveP;//存储手指移动到的位置

@end
@implementation LockView
//懒加载
- (NSMutableArray *)btns{
    if (_btns == nil) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}

//解析XIB文件时调用
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self addBtns];
    }
    return self;
}
//添加按钮
- (void)addBtns{
    for (int i = 0; i < 9; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i + 1;//用来记录按钮的标签（数字），方便下面连线时知道连线的方式
        //添加图片
        [btn setImage:[UIImage imageNamed:@"gesture_node_normal"] forState:UIControlStateNormal];
        
        [btn setImage:[UIImage imageNamed:@"gesture_node_highlighted"] forState:UIControlStateSelected];
        //不允许用户交互
        btn.userInteractionEnabled = NO;
        
        [self addSubview:btn];
    }
}
//设置位置
- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat col = 0;
    CGFloat row = 0;
    
    CGFloat btnW = 74;
    CGFloat btnH = 74;
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    
    CGFloat totalCol = 3;
    CGFloat margin = (self.bounds.size.width - totalCol * btnW) / (totalCol + 1);//间隔
    
    
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton *btn = self.subviews[i];
        
        col = i % 3;
        row = i / 3;
        
        btnX = margin + (margin + btnW) * col;
        btnY = (margin + btnH) * row;
        
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    }
}
//返回当前触摸点
- (CGPoint)pointWithTouches:(NSSet *)touches{
    //当前触摸点
    UITouch *touch = [touches anyObject];
    return [touch locationInView:self];
}
//返回选中的按钮
- (UIButton *)buttnWithPoint:(CGPoint)point{
    
    CGFloat width = 30; //触发的frame的宽度
    
    for (UIButton *btn in self.subviews) {
        CGFloat x = btn.center.x - width * 0.5;
        CGFloat y = btn.center.y - width * 0.5;
        CGRect frame = CGRectMake(x, y, width, width);
        
        if (CGRectContainsPoint(frame, point)){//触摸点pos在frame里
            return btn;
        }
    }
    return nil;
}
//第一次是触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //获取当前点
    CGPoint pos = [self pointWithTouches:touches];
    //是否触摸到按钮
    UIButton *btn = [self buttnWithPoint:pos];
    //如果触摸到按钮时，设为选中状态
    if (btn && btn.selected == NO)  {//避免重复选中
        btn.selected = YES;//触摸到按钮时，该按钮设为选中状态
        [_btns addObject:btn];//添加到数组里
    }
    
}
//后面是移动
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint pos = [self pointWithTouches:touches];
    _moveP = pos;//存储移动点用连线
    UIButton *btn = [self buttnWithPoint:pos];

    if (btn && btn.selected == NO) {
        btn.selected = YES;//触摸到按钮时，该按钮设为选中状态
        [_btns addObject:btn];//添加到数组里
    }
    //重绘（刷新图形样式）
    [self setNeedsDisplay];
}
//结束移动时
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//    [self.btns makeObjectsPerformSelector:@selector(setSelector:) withObject:@NO];//取消按钮的选择状态
    NSMutableString *str = [NSMutableString string];
    for (UIButton *btn in _btns) {
        [str appendFormat:@"%li",btn.tag];
        btn.selected = NO;
    }
    NSLog(@"%@",str);
    //清空数组
    [self.btns removeAllObjects];
    //重绘
    [self setNeedsDisplay];
}
//- (void)setNo{
//    
//}



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    if (!self.btns.count) {//清空数组时，不画线，直接返回。
        return;
    }
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    for (int i = 0; i < self.btns.count; i++) {
        UIButton *btn = _btns[i];
        if (i == 0) {//第一个点为起点
            [path moveToPoint:btn.center];
        }else{
            [path addLineToPoint:btn.center];
        }
    }
    
    //连接多出来的那根线
    [path addLineToPoint:_moveP];
    
    [[UIColor greenColor] set];
    path.lineWidth = 8;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineJoinRound;
    
    //渲染到视图
    [path stroke];
}


@end
